package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.controller.results.Code;
import com.itheima.controller.results.Result;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.system.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired//装配
    private UserService userService;

    //添加
    @PostMapping
    public Result save(User user){
        boolean flag = userService.save(user);
        //System.out.println(user);
        //使用三元运算符判断该操作是否成功
        return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR);
    }

    //修改
    @PutMapping
    public Result update(User user){
        boolean flag = userService.update(user);
        return new Result(flag ? Code.UPATE_OK : Code.UPATE_ERR);
    }

    //删除
    @DeleteMapping("/{uuid}")
    public Result delete(@PathVariable Integer uuid){
        boolean flag = userService.delete(uuid);
        return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR);
    }

    //查询单个user
    @GetMapping("/{uuid}")
    public Result get(@PathVariable Integer uuid){

        User user =  userService.get(uuid);

        //模拟出现异常,使用条件控制,便于测试结果
        if(uuid == 10) throw new BusinessException("查询出错了,请重试!",Code.GET_ERR);

        //使用三元运算符进行判断,并将查询得到的对象传递出去
        return new Result(null != user ? Code.GET_OK :Code.GET_ERR,user);
    }

    //分页查询
    @GetMapping("/{page}/{size}")
    public Result getAll(@PathVariable Integer page,@PathVariable Integer size){
        PageInfo<User> all =  userService.getAll(page,size);
        return new Result(null != all ? Code.GET_OK :Code.GET_ERR,all);
    }

    //登录,使用post隐藏密码
    @PostMapping("/loginssm")
    public Result login(String userName,String password){
        User user = userService.login(userName,password);
        return new Result(null != user ? Code.GET_OK : Code.GET_ERR,user);
    }
}
